const {
	db,
	dbCmd,
	result_success,
	result_error,
	appletInfoCollection,
	userCollection
} = require('../../common/constants')
const {
	mainSpaceId
} = require('config-main-space')
let mainCloud = uniCloud.init({
	provider: 'tencent',
	spaceId: mainSpaceId
})
const serviceProviderAppSdk = mainCloud.importObject('wmz-service-provider-app')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let cUser = await userCollection.doc(payload.uid).get()
	cUser = cUser.data[0]
	//获取当前应用
	let appletInfoData = await appletInfoCollection.doc(cUser.app_id).get()
	appletInfoData = appletInfoData.data[0]
	let _id = params._id
	let tprofitsharingData = await db.collection('wmzmall-profitsharing').where({
		share_account: params.share_account,
		app_id: appletInfoData._id
	}).get()
	tprofitsharingData = tprofitsharingData.data
	if (!_id && tprofitsharingData.length > 0) {
		return result_error('账号已存在')
	}
	if (params.type === 0) {
		params.type_name = '微信'
	} else if (params.type === 1) {
		params.type_name = '支付宝'
	}
	params.show = true
	params.app_id = appletInfoData._id
	params.shop_id = appletInfoData._id
	params.creator_id = payload.uid
	params.create_time = new Date().getTime()
	let tdb = uniCloud.database({
		provider: 'tencent',
		spaceId: mainSpaceId
	})
	if (!_id) {
		if (params.type === 0) {
			let profitsharingAddRes = await serviceProviderAppSdk.profitsharingAdd({
				_id: appletInfoData._id,
				account: params.share_account,
				name: params.share_name,
			})
			if (profitsharingAddRes.code === 200) {
				await db.collection('wmzmall-profitsharing').add(params)
				await tdb.collection('wmzmall-profitsharing').add(params)
			} else {
				return result_error(profitsharingAddRes.msg)
			}
		} else {
			let tradeRoyaltyRelationBindRes = await serviceProviderAppSdk.tradeRoyaltyRelationBind({
				app_id: appletInfoData.alipay.app_id,
				access_token: appletInfoData.alipay.app_auth_token,
				receiver_list: [{
					type: 'loginName',
					account: params.share_account,
					name: params.share_name,
				}],
				out_request_no: appletInfoData._id
			})
			if (tradeRoyaltyRelationBindRes.code === 200) {
				await db.collection('wmzmall-profitsharing').add(params)
				await tdb.collection('wmzmall-profitsharing').add(params)
			} else {
				return result_error(tradeRoyaltyRelationBindRes.msg)
			}
		}
	} else {
		await db.collection('wmzmall-profitsharing').doc(_id).update({
			share_ratio: params.share_ratio
		})
		await tdb.collection('wmzmall-profitsharing').doc(_id).update({
			share_ratio: params.share_ratio
		})
	}
	return result_success()
}